from urllib.request import build_opener, HTTPCookieProcessor, Request
from http.cookiejar import CookieJar
import io
import random
import json


def encode_data(data):
    try:
        return bytes(data, 'utf-8')
    except:
        return bytes(data)


def decode_data(data):
    return io.StringIO(data.read().decode('utf-8'))


def test_call_verion():
    base_url = 'http://192.168.56.114:8069'

    full_url = base_url + '/web/webclient/version_info'
    data = {
        "jsonrpc": "2.0",
        "method": "call",
        "id": random.randint(0, 1000000000),
        "params": {},
    }
    print('data:', data)

    data_json = json.dumps(data)
    request = Request(url=full_url, data=encode_data(data_json))
    request.add_header('Content-Type', 'application/json')
    cookie_jar = CookieJar()
    opener = build_opener(HTTPCookieProcessor(cookie_jar))
    response = opener.open(request, timeout=50000)
    print('response:', response)

    data = json.load(decode_data(response))
    print('data:', data)

    error = data.get('error')
    if error:
        print('error', error)
        raise error

    result = data.get('result')
    print('result:', result)
    return result


res = {
    'jsonrpc': '2.0',
    'id': 757431247,
    'result': {
        'server_version': '15.0-20221002',
        'server_version_info': [15, 0, 0, 'final', 0, ''],
        'server_serie': '15.0',
        'protocol_version': 1
    },

    'error': {
        #
    }


}


test_call_verion()
